package by.parfen.game.servlet;

import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;

import javax.json.JsonObject;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import by.parfen.game.datamodel.GameMessage;
import by.parfen.game.service.GameMessageService;
import by.parfen.game.service.impl.GameMessageServiceImpl;
import by.parfen.game.websocket.WebsocketClientEndpoint;

@WebServlet("/TestClient")
public class TestClient extends HttpServlet {
	private static final String WS_URL = "ws://localhost:8180/duelgame";
	private static final String WS_ONE_URL = WS_URL + "/websocket-one";
	private static final String WS_GAME_URL = WS_URL + "/websocket-game/root";
	private static final long serialVersionUID = 1L;

	private static final GameMessageService gameMessageService = new GameMessageServiceImpl();

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		try {
			// open websocket
			final WebsocketClientEndpoint clientEndPoint = new WebsocketClientEndpoint(new URI(WS_GAME_URL));
			System.out.println("Connected to " + WS_GAME_URL);

			// add listener
			clientEndPoint.addMessageHandler(new WebsocketClientEndpoint.MessageHandler() {
				public void handleMessage(String message) {
					System.out.println("Received message: " + message);
				}
			});

			// create test message
			GameMessage gameMessage = new GameMessage();
			gameMessage.setSubject("NEW_GAME");
			gameMessage.setContent("Some content");
			JsonObject jsonMessage = gameMessageService.encode(gameMessage);
			// send message to websocket
			clientEndPoint.sendMessage(jsonMessage.toString());

			// wait 5 seconds for messages from websocket
			Thread.sleep(5000);

		} catch (InterruptedException ex) {
			System.err.println("InterruptedException exception: " + ex.getMessage());
		} catch (URISyntaxException ex) {
			System.err.println("URISyntaxException exception: " + ex.getMessage());
		}
	}
}
